package com.yang.project.base.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectTest {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class<Person> personClass = Person.class;
        Person person = (Person) personClass.newInstance();
        //获取方法
        Method[] methods = personClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        Method m = personClass.getMethod("getName");
        System.out.println(m.invoke(person));
        Field field = personClass.getDeclaredField("name");
        field.setAccessible(true);
        field.set(person, "李四");
        System.out.println(m.invoke(person));
        //获取私有方法
        Method m2 = personClass.getDeclaredMethod("setName", String.class);
        m2.setAccessible(true);
        m2.invoke(person, "张三");
        System.out.println(m.invoke(person));
    }
}
